<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="员工工号" prop="jobNumber">
        <el-select
          v-model="formData.jobNumber"
          filterable
          remote
          reserve-keyword
          placeholder="请选择员工姓名"
          remote-show-suffix
          :remote-method="remoteMethod"
          @change="jobDropDown"
          :loading="loading"
        >
          <el-option
            v-for="(item, index) in options"
            :key="index"
            :label="item.jobNumber"
            :value="item.jobNumber"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="员工姓名" prop="userName">
        <el-select
          v-model="formData.userName"
          filterable
          remote
          reserve-keyword
          placeholder="请选择员工姓名"
          remote-show-suffix
          :remote-method="remoteMethod"
          @change="userDropDown"
          :loading="loading"
        >
          <el-option
            v-for="(item, index) in options"
            :key="index"
            :label="item.staffName"
            :value="item.staffName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="岗位" prop="post">
        <el-input disabled v-model="formData.post" placeholder="请输入岗位" />
      </el-form-item>
      <el-form-item label="班组编码" prop="teamCode">
        <el-input disabled v-model="formData.teamCode" placeholder="请输入班组编码" />
      </el-form-item>
      <el-form-item label="所属班组" prop="teamName">
        <el-input disabled v-model="formData.teamName" placeholder="请输入所属班组" />
      </el-form-item>
      <el-form-item label="奖惩类型" prop="rewardType">
        <el-select v-model="formData.rewardType" placeholder="请选择奖惩类型">
          <el-option
            v-for="(dict, index) in getIntDictOptions('punishments_type')"
            :key="index"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="奖惩金额" prop="rewardPrice">
        <el-input-number
          controls-position="right"
          :precision="2"
          :step="0.1"
          v-model="formData.rewardPrice"
          placeholder="请输入奖惩金额"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="奖惩理由" prop="rewardReason">
        <el-input
          type="textarea"
          show-word-limit
          maxlength="50"
          v-model="formData.rewardReason"
          placeholder="请输入奖惩理由"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions } from '@/utils/dict'
import * as AccountingRewardsPunishmentsApi from '@/api/payroll/shopWagesCalculate/awardPunishmentsManagement'
import * as componentApi from '@/api/componentApi'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const options = ref<any[]>([]) // 员工姓名
const loading = ref(false)
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  jobNumber: undefined,
  userName: undefined,
  teamCode: undefined,
  teamName: undefined,
  post: undefined,
  rewardType: undefined,
  rewardPrice: undefined,
  rewardReason: undefined
})
const formRules = reactive({
  jobNumber: [{ required: true, message: '员工工号不能为空', trigger: 'blur' }],
  userName: [{ required: true, message: '员工姓名不能为空', trigger: 'blur' }],
  rewardType: [{ required: true, message: '奖惩类型不能为空', trigger: 'blur' }],
  rewardPrice: [{ required: true, message: '奖惩金额不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await AccountingRewardsPunishmentsApi.getAccountingRewardsPunishments(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data =
      formData.value as unknown as AccountingRewardsPunishmentsApi.AccountingRewardsPunishmentsVO
    if (formType.value === 'create') {
      await AccountingRewardsPunishmentsApi.createAccountingRewardsPunishments(data)
      message.success(t('common.createSuccess'))
    } else {
      await AccountingRewardsPunishmentsApi.updateAccountingRewardsPunishments(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 员工姓名 */
const remoteMethod = async (query: string) => {
  loading.value = true
  try {
    const data = await componentApi.getStaffList(query)
    options.value = data
  } finally {
    loading.value = false
  }
}

/** 工号下拉选中 */
const jobDropDown = () => {
  options.value.map((item) => {
    if (formData.value.jobNumber === item.jobNumber) {
      formData.value.userName = item.staffName
    }
  })
}

/** 名字下拉选中 */
const userDropDown = () => {
  options.value.map((item) => {
    if (formData.value.userName === item.staffName) {
      formData.value.jobNumber = item.jobNumber
    }
  })
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    jobNumber: undefined,
    userName: undefined,
    teamCode: undefined,
    teamName: undefined,
    post: undefined,
    rewardType: undefined,
    rewardPrice: undefined,
    rewardReason: undefined
  }
  formRef.value?.resetFields()
}
</script>
